package com.yuwubao.uav.tool.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class ZipDownloadUtil {

    public static void main(String[] args) {

        String filePaths = "http://47.93.158.24:8780/zhiku/pic/pic_1538216018301.jpg|http://47.93.158.24:8780/zhiku/pic/pic_1538216018301.jpg";
        String fileNames = "1.jpg|2.jpg";
        String strZipPath = "";
        batDownload(strZipPath,filePaths,fileNames);
    }

    /*
     * 批量下载另存为
     */
    public static void batDownload(String strZipPath ,String filePaths, String fileNames) {

        try {

            ZipOutputStream out = new ZipOutputStream(new FileOutputStream(strZipPath));

            String[] files=filePaths.split("\\|",-1);

            String[] names=fileNames.split("\\|",-1);

            // 下载的文件集合

            int len;
            URL url;
            URLConnection con;
            InputStream  is;
            byte[] buffer = new byte[1024];

            for (int i = 0; i < files.length; i++) {

                // 构造URL            
                url = new URL(files[i]);
                //  打开连接            
                con=url.openConnection();
                //设置请求超时为30s
                con.setConnectTimeout(30 * 1000);
                // 输入流            
                 is = con.getInputStream();

                out.putNextEntry(new ZipEntry(names[i]));

                while ((len =  is.read(buffer)) > 0) {

                    out.write(buffer, 0, len);

                }

                out.closeEntry();

                is.close();

            }

            out.close();

        } catch (Exception e) {

            e.printStackTrace();

        }
    }




    /*
     * 另存为

    @RequestMapping("/saveAs.do")
    public @ResponseBody
    void saveAs(String filePath, String fileName) {

        try {
            File file = new File(filePath);
            // 设置文件MIME类型
            getResponse().setContentType(getMIMEType(file));
            // 设置Content-Disposition
            getResponse().setHeader(
                    "Content-Disposition",
                    "attachment;filename="
                            + URLEncoder.encode(fileName, "UTF-8"));
            // 获取目标文件的绝对路径
            String fullFileName = getRealPath("/upload/" + filePath);
            // System.out.println(fullFileName);
            // 读取文件
            InputStream ins = new FileInputStream(fullFileName);
            // 放到缓冲流里面
            BufferedInputStream bins = new BufferedInputStream(ins);
            // 获取文件输出IO流
            // 读取目标文件，通过response将目标文件写到客户端
            OutputStream outs = getResponse().getOutputStream();
            BufferedOutputStream bouts = new BufferedOutputStream(outs);
            // 写文件
            int bytesRead = 0;
            byte[] buffer = new byte[8192];
            // 开始向网络传输文件流
            while ((bytesRead = bins.read(buffer, 0, 8192)) != -1) {
                bouts.write(buffer, 0, bytesRead);
            }
            bouts.flush();// 这里一定要调用flush()方法
            ins.close();
            bins.close();
            outs.close();
            bouts.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    */

    /*
     * 批量下载另存为

    @RequestMapping("/batDownload.do")
    public @ResponseBody
    void batDownload(String filePaths, String fileNames) {
        String tmpFileName = "work.zip";
        byte[] buffer = new byte[1024];
        String strZipPath = getRealPath("/upload/work/"+tmpFileName);
        try {
            ZipOutputStream out = new ZipOutputStream(new FileOutputStream(
                    strZipPath));
            String[] files=filePaths.split("\\|",-1);
            String[] names=fileNames.split("\\|",-1);
            // 下载的文件集合
            for (int i = 0; i < files.length; i++) {
                FileInputStream fis = new FileInputStream(getRealPath("/upload/"+files[i]));
                out.putNextEntry(new ZipEntry(names[i]));
                //设置压缩文件内的字符编码，不然会变成乱码
                out.setEncoding("GBK");
                int len;
                // 读入需要下载的文件的内容，打包到zip文件
                while ((len = fis.read(buffer)) > 0) {
                    out.write(buffer, 0, len);
                }
                out.closeEntry();
                fis.close();
            }
            out.close();
            saveAs("work/"+tmpFileName, tmpFileName);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
*/
    /**
     * 根据文件后缀名获得对应的MIME类型。
     *
     * @param file
     */
//    private String getMIMEType(File file) {
//        String type = "*/*";
//        String fName = file.getName();
//        // 获取后缀名前的分隔符"."在fName中的位置。
//        int dotIndex = fName.lastIndexOf(".");
//        if (dotIndex < 0) {
//            return type;
//        }
//        /* 获取文件的后缀名 */
//        String end = fName.substring(dotIndex, fName.length()).toLowerCase();
//        if (end == "")
//            return type;
//        // 在MIME和文件类型的匹配表中找到对应的MIME类型。
//        for (int i = 0; i < MIME_MapTable.length; i++) {
//            if (end.equals(MIME_MapTable[i][0]))
//                type = MIME_MapTable[i][1];
//        }
//        return type;
//    }
//
//    private final String[][] MIME_MapTable = {
//            // {后缀名， MIME类型}
//            { ".doc", "application/msword" },
//            { ".docx",
//                    "application/vnd.openxmlformats-officedocument.wordprocessingml.document" },
//            { ".xls", "application/vnd.ms-excel" },
//            { ".xlsx",
//                    "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" },
//            { ".pdf", "application/pdf" },
//            { ".ppt", "application/vnd.ms-powerpoint" },
//            { ".pptx",
//                    "application/vnd.openxmlformats-officedocument.presentationml.presentation" },
//            { ".txt", "text/plain" }, { ".wps", "application/vnd.ms-works" },
//            { "", "*/*" } };
}
